package service.serviceimpl;

import dao.CartDao;
import dao.GoodsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.Cart;
import pojo.Goods;
import service.CartService;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Service
public class CartServiceimpl implements CartService {

    @Autowired
    CartDao cartDao;
    @Autowired
    GoodsDao goodsDao;
    @Override
    public List<Cart> selectAll(int id) {
         List<Cart> list = cartDao.selectAll(id);
        Iterator ite = list.iterator();
        List<Cart> list1 = new ArrayList<>();
        while(ite.hasNext()){
            Cart cart = (Cart)ite.next();
            int goodsId =cart.getPid();
            Goods goods = goodsDao.selectOne(goodsId);
            cart.setGoods(goods);
            list1.add(cart);
        }
        return list1;
    }

    @Override
    public void addGoods(int goodsId, int num, int userId) {

        Cart cart = cartDao.selectOne(userId,goodsId);
        if(cart==null){
            Goods goods = goodsDao.selectOne(goodsId);
            int price = goods.getPrice();
            cartDao.insertOne(userId,goodsId,num,price);
        }else{
            int number = cart.getNum();
            if((number+num)<=0){
                goodsDao.deleteOne(goodsId,userId);
            }else{
                Goods goods = goodsDao.selectOne(goodsId);
                int price = goods.getPrice();

                cart.setMoney(cart.getMoney()+(num*price));
                cart.setNum(cart.getNum()+num);

                cartDao.updateGoods(cart.getId(),cart.getNum(),cart.getMoney(),cart.getPid());
        }



        }

    }
}
